/**
 * 处理流式响应
 * @param {object} response - 流式响应对象
 * @returns {Promise<object>} - 返回处理后的完整响应内容和消息ID
 */
export const processStreamResponse = async (response) => {
    return new Promise((resolve, reject) => {
        let fullResponse = '';
        let thinking = '';
        let buffer = '';
        let messageId = '';

        response.data.on('data', (chunk) => {
            buffer += chunk.toString();
            const lines = buffer.split('\n\n');
            lines.slice(0, -1).forEach((line) => {
                if (line.startsWith('data: ')) {
                    const jsonData = line.substring(6);
                    if (jsonData === '[DONE]') {
                        console.log('Stream completed');
                        return;
                    }
                    try {
                        const parsedData = JSON.parse(jsonData);
                        if (parsedData.choices) {
                            const delta = parsedData.choices[0].delta;
                            let content = delta.content || '';
                            if (parsedData.choices[0].delta.type === 'thinking') {
                                thinking += content;
                            } else if (parsedData.choices[0].delta.type === 'text') {
                                fullResponse += content;
                            }
                        }
                        if (parsedData.message_id) {
                            messageId = parsedData.message_id;
                        }
                    } catch (error) {
                        logger.error('Error parsing chunk:', error);
                    }
                }
            });
            buffer = lines[lines.length - 1];
        });

        response.data.on('end', () => {
            if (buffer) {
                const lines = buffer.split('\n\n');
                lines.forEach((line) => {
                    if (line.startsWith('data: ')) {
                        const jsonData = line.substring(6);
                        if (jsonData === '[DONE]') {
                            console.log('Stream completed');
                            return;
                        }
                        try {
                            const parsedData = JSON.parse(jsonData);
                            if (parsedData.choices) {
                                const delta = parsedData.choices[0].delta;
                                let content = delta.content || '';
                                if (parsedData.choices[0].delta.type === 'thinking') {
                                    thinking += content;
                                } else if (parsedData.choices[0].delta.type === 'text') {
                                    fullResponse += content;
                                }
                            }
                            if (parsedData.message_id) {
                                messageId = parsedData.message_id;
                            }
                        } catch (error) {
                            logger.error('Error parsing chunk:', error);
                        }
                    }
                });
            }
            resolve({ msg: fullResponse, thinking: thinking, messageId: messageId });
        });

        response.data.on('error', (error) => {
            logger.error('Stream error:', error);
            reject(error);
        });
    });
};

